﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Text;

namespace Web.Controllers.Filter
{
    /// <summary>
    /// 拦截Action的异常
    /// </summary>
    public class ExceFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Action执行完成后
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Exception != null)
            {
                //1.获取异常对象
                Exception ex = filterContext.Exception;

                //2.记录异常日志  
                string controllerName = filterContext.ActionDescriptor.RouteValues["controller"].ToString();//ControllerName
                string actionName = filterContext.ActionDescriptor.RouteValues["action"].ToString();//ActionName
                string ExceptionMessage = filterContext.Exception.GetBaseException().Message;//异常消息
                string ExecptionType = filterContext.Exception.GetBaseException().GetType().ToString();//异常类型
                string ExecptionStackTrace = filterContext.Exception.GetBaseException().StackTrace.ToString();//异常跟踪
                var Execresult = new StringBuilder();
                Execresult.AppendFormat(string.Format("在执行 controller[{0}] 的 action[{1}] 时产生异常", controllerName, actionName));
                //Execresult.AppendLine();
                //Execresult.AppendFormat(string.Format("异常消息：{0}", ExceptionMessage));
                //Execresult.AppendLine();
                //Execresult.AppendFormat(string.Format("异常类型：{0}", ExecptionType));
                //Execresult.AppendLine();
                //Execresult.AppendFormat(string.Format("异常跟踪StackTrace：{0}", ExecptionStackTrace));
                //Execresult.AppendLine();
                LogHelper.Error(Execresult.ToString(), LogHelper.logsSource.微信,ex:filterContext.Exception);
                ////3.重定向友好页面  
                //filterContext.Result = new RedirectResult("~/error.html");

                //或者输出异常信息
                //var excResult = new ContentResult();
                //excResult.Content = Execresult.ToString();
                //filterContext.Result = excResult;

                //4.标记异常已经处理完毕
                //filterContext.ExceptionHandled = true;
            }
        }
    }
}